package com.maoning.ware.service.impl;

import com.maoning.common.constant.WareConstant;
import com.maoning.ware.entity.PurchaseDetailEntity;
import com.maoning.ware.service.PurchaseDetailService;
import com.maoning.ware.service.WareSkuService;
import com.maoning.ware.vo.MergeVo;
import com.maoning.ware.vo.PurchaseDoneItemVo;
import com.maoning.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoning.common.utils.PageUtils;
import com.maoning.common.utils.Query;

import com.maoning.ware.dao.PurchaseDao;
import com.maoning.ware.entity.PurchaseEntity;
import com.maoning.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询为领取的采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        final QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0).or().eq("status", 1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null){
            final PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //        确认采购单的状态是0或者是1才可以合并
        final PurchaseEntity byId1 = this.getById(purchaseId);
        if(byId1.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || byId1.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGEND.getCode()){
            final List<Long> items = mergeVo.getItems();
            final Long finalPurchaseId = purchaseId;
            final List<PurchaseDetailEntity> collect = items.stream().map(id -> {
                final PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(id);
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGEND.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
            final PurchaseEntity byId = this.getById(finalPurchaseId);
            byId.setUpdateTime(new Date());
            this.updateById(byId);
        }
    }

    /**
     * 用来模拟的外部接口,主要提供给别人的app去做[领取采购单]的操作
     * @param ids
     */
    @Transactional
    @Override
    public void receivedPurchase(List<Long> ids) {
//        1.根据id获得采购单,更新时间,更新状态(只对新建和分配的做操作)
        final List<PurchaseEntity> collect = ids.stream().map(id -> {
            final PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            return item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGEND.getCode();
        }).map(e -> {
            e.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            e.setUpdateTime(new Date());
            return e;
        }).collect(Collectors.toList());
//        2.更新采购单
        this.updateBatchById(collect);
//        3.更新采购需求
        collect.forEach(purchase -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByPurchaseId(purchase.getId());
            final List<PurchaseDetailEntity> collect1 = purchaseDetailEntities.stream().map(item -> {
                final PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
        });
    }

    @Transactional
    @Override
    public void donePurchase(PurchaseDoneVo purchaseDoneVo) {
//        1.更新采购需求
        AtomicBoolean flag = new AtomicBoolean(true);
        final List<PurchaseDoneItemVo> purchaseDoneItemVos = purchaseDoneVo.getItems();
        final List<PurchaseDetailEntity> detailEntities = purchaseDoneItemVos.stream().map(item -> {
            final PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            final Integer status = item.getStatus();
            if (status == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag.set(false);
            } else {
                final PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                //        3.商品入库
                wareSkuService.addStock(byId.getSkuId(), byId.getWareId(), byId.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntities);
//        2.更新采购单(如果有未完成的需求,给采购单状态设置异常)
        final PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setStatus(flag.get() ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);
    }

}